package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return  dateList   turnoverList
     */
    @Override
    public Result<TurnoverReportVO> turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.获取每一天的时间，然后封装到dateList集合中 假如5.2-5.8之间的每一天时间
            //创建一个空的集合，用来承载每一天的日期
        List<LocalDate> dateList=new ArrayList<LocalDate>();
        dateList.add(begin);

        while (!begin.equals(end)){
            //在原来的日期基础之上加1
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //2.获取每一天所对应的营业额，然后封装到turnoverList集合中

        List<Double> turnoverList=new ArrayList<>();

        dateList.forEach(date->{
            //2.1 当天的最小和最大时间
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max =LocalDateTime.of(date, LocalTime.MAX);

            //2.2 调用mapper接口
            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("min",min);
            map.put("max",max);
            Double turnover = orderMapper.sumByMap(map);
            turnoverList.add(turnover==null ?0:turnover);
        });


        //3.封装数据，并返回
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();


        return Result.success(vo);
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<UserReportVO> userStatistics(LocalDate begin, LocalDate end) {
        //1.获取x轴的数据，每一天的时间日期
        List<LocalDate> dateList=new ArrayList<LocalDate>();
        dateList.add(begin);

        while (!begin.equals(end)){
            //在原来的日期基础之上加1
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //定义两个空的集合，用来承载总用户量和新用户量
        List<Integer> totalUserList=new ArrayList<>();
        List<Integer> newUserList=new ArrayList<>();

        dateList.forEach(date->{
            //2.1 当天的最小和最大时间
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max =LocalDateTime.of(date, LocalTime.MAX);
            //2.获取当天的总用户量  sql: select count(id) from user where create_time <max
            Map map=new HashMap();
            map.put("max",max);
            Integer totalUserCount = userMapper.getUserCount(map);
            //3.获取当天的新用户量  sql: select count(id) from user where create_time <max and create_time>min
            map.put("min",min);
            Integer newUserCount = userMapper.getUserCount(map);

            totalUserList.add(totalUserCount);
            newUserList.add(newUserCount);

        });

        //4.返回数据
        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();

        return Result.success(vo);
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return  x轴每一天的日期列表
     */
    @Override
    public Result<OrderReportVO> ordersStatistics(LocalDate begin, LocalDate end) {
        //1.获取x轴的数据，每一天的时间日期
        List<LocalDate> dateList=new ArrayList<LocalDate>();
        dateList.add(begin);

        while (!begin.equals(end)){
            //在原来的日期基础之上加1
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //定义两个空的集合，用来承载总用户量和新用户量
        List<Integer> orderCountList=new ArrayList<>();//[1,4,6,8]
        List<Integer> validOrderCountList=new ArrayList<>();


        //对每一天的数据操作
        dateList.forEach(date-> {
            //2.1 当天的最小和最大时间
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap();
            map.put("max",max);
            map.put("min",min);
            //2.获取每天的总订单数量
            Integer totalOrderCount = orderMapper.getOrderCount(map);
            //3.获取每天的有效订单数量
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderCount(map);

            orderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);

        });

        //4.获取时间范围内的总订单数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //5.获取时间范围内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //6.获取时间范围内的订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        }

        //7.数据封装，然后返回
        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return Result.success(vo);
    }

    /**
     * 销量排名
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<SalesTop10ReportVO> top10(LocalDate begin, LocalDate end) {

        //1.日期格式转化成包含时分秒的时间localDateTime
           LocalDateTime newBegin=LocalDateTime.of(begin,LocalTime.MIN);
           LocalDateTime newEnd = LocalDateTime.of(end, LocalTime.MAX);
        //2.查询mysql获取对应的数据 ["name":"1,2,3,4","number":"12,13,14"]
        List<GoodsSalesDTO> salesTop10List = orderMapper.getSalesTop10(newBegin, newEnd);

        //3.菜品|套餐名称集合
        List<String> nameList = salesTop10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());

        //4菜品名称所对应的销量集合
        List<Integer> numberList = salesTop10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        //5.封装数据并返回
        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();


        return Result.success(vo);
    }

    /**
     * 报表的导出功能
     */
    @Override
    public void export(HttpServletResponse response) {
        try {
         //2.2 获取近30天的时间
            LocalDate begin = LocalDate.now().minusDays(30); //-30
            LocalDate end = LocalDate.now().minusDays(1);//-1


            //1.获取模板文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //2.获取excel文件对象
        XSSFWorkbook excel=new XSSFWorkbook(inputStream);
        XSSFSheet sheet = excel.getSheet("Sheet1");

        //2.1 为第二行的第二个单元格赋值，时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+begin+"至"+end);

        //2.3 概览数据赋值
            //2.3.1 获取近1个月内的相关数据
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
            //2.3.2 excel相关
            XSSFRow row = sheet.getRow(3);
            //营业额单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row=sheet.getRow(4);
            //有效订单
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            row.getCell(4).setCellValue(businessData.getUnitPrice());

         //2.4 明细数据-每一天的
            for (int i = 0; i <30 ; i++) {
                //2.4.1 获取每一天的对应的数据
                    //获取每一天的时间
                LocalDate date=begin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //2.4.2 excel相关操作
               row= sheet.getRow(7+i);
               //日期
                row.getCell(1).setCellValue(date.toString());
                //营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //有效订单
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //写操作
            excel.write(response.getOutputStream());

            //关闭资源
            excel.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
